const db = require('../db/db');
const uuidV1 = require('uuid/v1');

module.exports = {
    createSession(user){
        var uuid = uuidV1();
        var token = `${user.id}@${uuid}`;
        var time = Date.now();
        return db.add('sessions', {token:token, user:user.id, ctime:time});
    },
    destorySession(token){
        var s = db.get('sessions', x=>{
            return x.token == token;
        })

        return s && db.delete('sessions', s.id);
    },
    getSession(token){
        var s = db.get('sessions', x=>{
            return x.token == token;
        });

        if(s == null){
            return null;
        }

        if(s.ctime + 24 * 60 * 60 * 1000 < Date.now()){
            db.delete('sessions', s.id);
            return null;
        }
        return s;
    }
}